package com.yirui.bridge.core;

import com.yirui.bridge.tcp.NettyTcpClient;
import com.yirui.bridge.tcp.server.AgentServer;
import com.yirui.bridge.udp.NettyUdpClient;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 服务管理器
 * @author Dujie
 * @create 2025/7/24
 * @since 1.0.0
 */
public class ServerManager {
    private static Map<String, Object> protocolClients = new ConcurrentHashMap<>();
    static {
        protocolClients.put("tcp", NettyTcpClient.class);
        protocolClients.put("udp", NettyUdpClient.class);
        protocolClients.put("tcpServer", AgentServer.class);
    }
    public Server getServer(String protocol, boolean init) throws Exception {
        Object obj = protocolClients.get(protocol);
        if(obj != null){
            if(obj instanceof Class){
                if(init) {
                    obj = ((Class) obj).newInstance();
                    protocolClients.put(protocol, obj);
                }else{
                    return null;
                }
            }
            return (Server)obj;
        }
        return null;
    }

    public Server getServer() throws Exception {
        return getServer(SourceTypeContext.getType(), false);
    }

    public void stop(){
        protocolClients.forEach((key, o)->{
            if(o instanceof Server){
                ((Server)o).stop();
            }
        });
    }
}
